package cn.tedu.egweibo7.controller;


import cn.tedu.egweibo7.base.Utils.CacheUtil;
import cn.tedu.egweibo7.base.response.JsonResult;
import cn.tedu.egweibo7.mapper.WeiboMapper;
import cn.tedu.egweibo7.pojo.dto.WeiboDTO;
import cn.tedu.egweibo7.pojo.entity.Weibo;
import cn.tedu.egweibo7.pojo.vo.UserVO;
import cn.tedu.egweibo7.pojo.vo.WeiboDetailVO;
import cn.tedu.egweibo7.pojo.vo.WeiboListVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Slf4j
@Validated
@RestController
@Api(tags = "02.微博模块")
@RequestMapping("/v1/weibo/")
public class WeiboController {

    @Autowired
    private WeiboMapper weiboMapper;

    @Autowired
    private CacheUtil cacheUtil;

    @ApiOperation(value = "发布微博")
    @PostMapping("insert")
    public JsonResult insert(@RequestBody @Validated WeiboDTO weiboDTO,
                             @ApiIgnore HttpSession httpSession) {
        log.debug("weiboDTO={}", weiboDTO);
        UserVO userVO = (UserVO) httpSession.getAttribute("user");
        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboDTO, weibo);
        weibo.setCreated(new Date());
        weibo.setUserId(userVO.getId());
        weiboMapper.insert(weibo);

        return JsonResult.ok();
    }

    @ApiOperation(value = "微博首页列表")
    @GetMapping("selectIndex")
    public JsonResult selectIndex() {
        Serializable weiboList = cacheUtil.get("weiboList");
        if (weiboList != null) {
            System.out.println("从redis中拿数据");
            return JsonResult.ok(weiboList);
        }
        List<WeiboListVO> weiboListVOS = weiboMapper.selectIndex();
        cacheUtil.setExpire("weiboList", (Serializable) weiboListVOS, 30);
        System.out.println("从MySQL中拿数据");

        return JsonResult.ok(weiboListVOS);
    }

    @ApiOperation(value = "微博详情页")
    @GetMapping("selectById")
    @ApiImplicitParam(name = "id", value = "微博编号", required = true, dataType = "long")
    public JsonResult selectById(@Range(min = 200, max = 300, message = "微博ID必须在200~300之间") @RequestParam Long id) {
        log.debug("id={}", id);
        WeiboDetailVO weiboDetailVO = weiboMapper.selectById(id);
        return JsonResult.ok(weiboDetailVO);
    }


}
